﻿//客户页面

//时间的
var calendarDateFormat = myApp.calendar({
    input: '#_validDate',
    closeOnSelect:true,
});
var calendarDateFormat = myApp.calendar({
    input: '#tarrivalTime',
    closeOnSelect:true,
});
//var pickerDevice = myApp.picker({
//input: '#add_sysStatus',
//cols: [
//  {
//    textAlign: 'center',
//    values: ['正常', '待审']
//  }
//]
//});
var EDITMODE=false;
(function(){
    var customer={
        init:function(){
            this.bindEvents();
            getCustomer();//获取客户列表
            this.GetSale("_salesUserID");//业务下拉
            this.GetPurchase("_purchaseUserID");//采购下拉
            this.getSupplierRoles();//获取供应商角色
        },
        bindEvents:function(){
            var self=this;
            //添加客户
            $("#add_btn").on("click",function(){
                $("#add_userName").prop("disabled",false)
                $("#add_mobile").prop("readonly",false);
                $("#customer_form_title").text(_("客户新增"));
                if($('#form_RoleName').html()!=""){
                    $('#form_RoleName').multipleSelect("setSelects", []); //清空
                }
                EDITMODE=false;
                $("#form_data input[type=text],#form_data textarea").val("");
                $("#form_power_label_box").hide();
                self.GetSale("combo_sales");
                self.GetPurchase("combo_purchases");
                myApp.popup(".customer_form_box");
                $("#reset_btn").show();
            });
            //筛选
            $("#confirm_btn").on("click",function(){
                getCustomer();//获取客户列表
                myApp.closeModal(".customer_filter_box");
            });

            //移交
            $("#transfer").on("click",function(){
                myApp.popup(".popup_ModifySalesUserID_box");
                self.GetSale("_salesUserIDs");//业务下拉 9-24
            });
            //分销
            $("#distribution").on("click",function(){
                myApp.popup(".popup_Dist_box");
//				$(".Dist_box").show();
            });
            //全选
            $("#th_check_all").on("click",function(){
                var $this=$(this).children().children("span");
                $this.toggleClass("selected")
                if($this.hasClass("selected")){
                    $("#stock_body .check_list_box").children("span").addClass("selected");
                    $("tbody tr.data_tr").addClass("tr_select_color");
                    $("#transfer,#role_btn,#discounts_btn").css("background-color", primary_color);
                    $("#transfer,#role_btn,#discounts_btn").attr("disabled", false);
                }else{
                    $("tbody tr.data_tr").removeClass("tr_select_color");
                    $("#stock_body .check_list_box").children("span").removeClass("selected");
                    clearBtn();
                }
            });
            //列表的勾选框 check_rel
            $("#stock_body").on("click",".check_rel",function(){
                $(this).find('.check_list_box').children("span").toggleClass("selected");
                if($(this).find('.check_list_box').children("span").hasClass("selected")){
                    $(this).closest("tr").addClass('tr_select_color');
                }else{
                    $(this).closest("tr").removeClass('tr_select_color');
                }

                //判断是否全选
                var length=$("#stock_body .check_list_box span").length;
                var checkLength=$("#stock_body .check_list_box span.selected").length;
                if(checkLength>0){
                    if(length==checkLength){
                        $("#th_check_all").find('span').addClass("selected");
                    }else{
                        $("#th_check_all").find('span').removeClass("selected");
                    }
                    $("#transfer,#role_btn,#discounts_btn").css("background-color", primary_color);
                    $("#transfer,#role_btn,#discounts_btn").attr("disabled", false);
                }else{
                    clearBtn();
                }
            });
            //状态切换搜索
            $("#_sysStatus ul li").click(function(){
                $(this).addClass("add_blue").siblings().removeClass("add_blue");
                getCustomer();
            });
            //编辑
            $("#stock_body").on("click",".handle_div a.modify_btn",function(){
                $("#add_userName").prop("disabled",true)  //所有角色不能修改账号

                $(".control_ul").hide(); //隐藏供应商角色下拉框
                var id=$(this).attr("data-id");
                self.GetSale("combo_sales");
                self.GetPurchase("combo_purchases");
                $("#customer_form_title").text(_("客户编辑"));
                EDITMODE=true;
                $("#form_power_label_box").show();
                self.bindData(id,"form_data");
                if(RoleID!=1){
                    if($(this).attr("data-mobile")!=""){
                        $("#add_mobile").attr("readonly","readonly");
                    }else{
                        $("#add_mobile").removeAttr("readonly");
                    }
                }else{
                    $("#add_mobile").removeAttr("readonly");
                }


                myApp.popup(".customer_form_box");
            });

            //修改权限产品 start
            $("#stock_body").on("click",".handle_div a.power_btn",function(){
                    myApp.popup('.power_form_box');
                    $('#form_data_power').attr('data-id',$(this).attr('data-id'));
                    self.bindPowerNew($('#form_data_power').attr('data-id'));
            });

            $("#change_type span").click(function(){
                $(this).toggleClass("active").siblings().removeClass("active");
                var type=$(this).attr('data-type');
                $('#form_power_label_box_type .power_label').hide();
                $('#form_power_label_box_type .power_label[data-type='+type+']').show();
            })

            $("#customer_power_btn").click(function(){
                var requestJson={};
                requestJson.CustomerID=$("#form_data_power").attr("data-id")
                var inventorylistCb=$('.form_group input[type=checkbox]:checked');
                var data1=[];
                var data2=[];
                var data3=[];
                var data4=[];
                var data5=[];
                var data6=[];
                var data7=[];
                var ids='';
                for(var i=0;i<inventorylistCb.length;i++){
                    if(inventorylistCb[i].value<200){
                        data1.push(inventorylistCb[i].value);
                    }else if (inventorylistCb[i].value>=200&&inventorylistCb[i].value<300){
                        data2.push(inventorylistCb[i].value);
                    }else if (inventorylistCb[i].value>=300&&inventorylistCb[i].value<400){
                        data3.push(inventorylistCb[i].value);
                    }else if (inventorylistCb[i].value>=400&&inventorylistCb[i].value<500){
                        data4.push(inventorylistCb[i].value);
                    }else if (inventorylistCb[i].value>=500&&inventorylistCb[i].value<600){
                        data5.push(inventorylistCb[i].value);
                    }else if(inventorylistCb[i].value>=600&&inventorylistCb[i].value<700){
                        data6.push(inventorylistCb[i].value);
                    }else if(inventorylistCb[i].value>=700&&inventorylistCb[i].value<800){
                        data7.push(inventorylistCb[i].value);
                    }
                }
                if(data1.length>=1){
                    ids+=data1.join(',')+'|';
                }
                if(data2.length>=1){
                    ids+=data2.join(',')+'|';
                }
                if(data3.length>=1){
                    ids+=data3.join(',')+'|';
                    console.log(ids)
                }
                if(data4.length>=1){
                    ids+=data4.join(',')+'|';
                }
                if(data5.length>=1){
                    ids+=data5.join(',')+'|';
                }
                if(data6.length>=1){
                    ids+=data6.join(',')+'|';
                }
                if(data7.length>=1){
                    ids+=data7.join(',')+'|';
                }
                if(ids){
                    requestJson.Control_Column_Ids=ids.substring(0,ids.lastIndexOf('|'))
                }
                $.ajax({
                    url: "/Team/SubmitCustomerRights",//提交地址
                    type: "POST",//提交方式
                    data: JSON.stringify(requestJson),
                    async: false,
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        var _result = JSON.parse(result);//返回修改成功的信息--{msgcode: true, msginfo: "修改成功"}
                        if(_result.msgcode==true){
                            myApp.alert(_(_result.msginfo));
                             $(".power_form_box").hide();
                             getCustomer;//加载客户
                        }else{
                            myApp.alert(_(_result.msginfo));
                        }
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown){
                        myApp.alert(_("网络超时，请重试"));
                    }
                });

            });
            //修改权限产品 end


            //供应商角色列表显示start
            $("#control_id,#control_id_role").on("click",function(){
                var dis=$(".control_ul").css('display');
                if(dis=='none'){
                    $(".control_ul").show();
                }else {
                    $(".control_ul").hide();
                }
            });

            //供应商全选
            $("body").on('click','#control_id .is_parent',function(){
                $(".control_ul").show();
                var isChange = $(this).prop("checked");
                var type = $(this).attr("data-lant");
                if(isChange){
                    $('#control_id .check_child_li').find('input[data-lant="'+type+'"]').prop('checked',true);
                }else {
                    $('#control_id .check_child_li').find('input[data-lant="'+type+'"]').removeAttr("checked");
                }
                self.stringInput('#control_id');
            });
            //供应商单选---判断全选
            $("body").on('click','#control_id .check_child',function(){
                $(".control_ul").show();
                var type = $(this).attr("data-lant");
                var isChangeLen = $('#control_id .check_child_li input[data-lant="'+type+'"]:checked').size();
                var isChangeLenNo = $('#control_id .check_child_li input[data-lant="'+type+'"]').size();
                if(isChangeLen==isChangeLenNo){
                    $('#control_id .is_parent_li').find('input[data-lant="'+type+'"]').prop('checked',true);
                }else {
                    $('#control_id .is_parent_li').find('input[data-lant="'+type+'"]').removeAttr("checked");
                }
                self.stringInput('#control_id');
            });


            //批量供应商选择
            $("body").on('click','#control_id_role .is_parent',function(){
                $(".control_ul").show();
                var isChange = $(this).prop("checked");
                var type = $(this).attr("data-lant");
                if(isChange){
                    $('#control_id_role .check_child_li').find('input[data-lant="'+type+'"]').prop('checked',true);
                }else {
                    $('#control_id_role .check_child_li').find('input[data-lant="'+type+'"]').removeAttr("checked");
                }
                self.stringInput('#control_id_role');
            });
            $("body").on('click','#control_id_role .check_child',function(){
                $(".control_ul").show();
                var type = $(this).attr("data-lant");
                var isChangeLen = $('#control_id_role .check_child_li input[data-lant="'+type+'"]:checked').size();
                var isChangeLenNo = $('#control_id_role .check_child_li input[data-lant="'+type+'"]').size();
                if(isChangeLen==isChangeLenNo){
                    $('#control_id_role .is_parent_li').find('input[data-lant="'+type+'"]').prop('checked',true);
                }else {
                    $('#control_id_role .is_parent_li').find('input[data-lant="'+type+'"]').removeAttr("checked");
                }
                self.stringInput('#control_id_role');
            });
            //供应商角色列表显示end


            //权限
//          $("#stock_body").on("click",".handle_div a.edit_power_btn",function(){
//          	$("#_power input[type=checkbox]").each(function(){
//				   	$(this).attr("checked",false);
//				});
//          	var id=$(this).attr("data-id");
//          	$("#power_CustomerID").val(id);
//          	self.bindPower(id);
//          });
//          $("#power_btn").on("click",function(){
//          	self.powerCustomer();
//          });
            //提现
            $("#stock_body").on("click",".handle_div a.Withdrawals_btn",function(){
                myApp.popup(".Cash_box");
//          	$(".Cash_box").show();
                var id=$(this).attr("data-id");
                self.TxAccountLoad(0);
                $.ajax({
                    url: "/Customer/GetCustomerInfo",//提交地址
                    type: "POST",//提交方式
                    data: "{'CustomerID':'" + id + "'}",
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        var _result = eval('(' + result + ')');//eval()解析单个json对象
                        //客户申请提现
                        $("#_customID").val(_result.CustomerID);
                        $("#_nickNa").val(_result.NickName);
                        $("#_realNam").val(_result.RealName);
                        $("#_bala").val(_result.Balance);
                        $("#_usdBala").val(_result.USDBalance);
                    }
                });
            });
            //审核
            $("#stock_body").on("click",".handle_div a.aduit_btn",function(){
//          	$(".Active_box").show();
                myApp.popup('.popup_Active_box');
                var id=$(this).attr("data-id");
                $("#active_customerID").val(id);
                self.GetPurchase("active_purchases");
                self.GetSale("active_sales");
                self.bindData(id,"activecustomer_form");
                // self.bindPower(id);//绑定客户权限
            });
            //调节
            $("#stock_body").on("click",".handle_div a.adjust_btn",function(){
                var id=$(this).attr("data-id");
//          	 $(".Adjust_box").show();
                myApp.popup(".Adjust_box");
                $.ajax({
                    url: "/Customer/GetCustomerInfo",//提交地址
                    type: "POST",//提交方式
                    data: "{'CustomerID':'" + id + "'}",
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        var _result = eval('(' + result + ')');//eval()解析单个json对象
                        //调节客户余额
                        $("#adjust_cuID").val(_result.CustomerID);
                        $("#_nickNam").val(_result.NickName);
                        $("#_reNam").val(_result.RealName);
                        $("#_ba").val(_result.Balance);
                        $("#_usdba").val(_result.USDBalance);
                    }
                });
            });

            //点击全选
//			$("#checkbox_check_all").on("click",function(){
//				$(this).toggleClass("selected");
//				if($(this).hasClass("selected")){
//					$("#stock_body .check_list_box").children("span").addClass("selected");
//				}else{
//					$(".check_list_box").children("span").removeClass("selected");
//				}
//			});

            //点击行展开详情
            $("#product_table").on("click", "tr.data_tr td", function (event) {
                var td_input = $(this).index();
                if (td_input == 0 || td_input==9) {
                    //勾选框不展开详情
                } else {
                    $(this).parent("tr").next(".stock_detail").slideToggle(0);
                }
            });
            //其他筛选条件点击添加样式、可多选
            $("#product_term_box").on("click", ".term span", function () {
                $(this).toggleClass("active");
                //筛选点击重量时，重量框的值
                var name = $(this).parent().attr("data-type");
                if (name = "Weight") {
                    self.getWeight();
                }
            });
            $("#show_term_btn").on("click", function () {
                myApp.popup(".customer_filter_box");
            });
            //切换白钻加点 白钻倍率
            $("#rebate_switch").on("click",function(){
                var rebate_type=$(this).attr("data-type");
                if(rebate_type==1){
                    $(this).attr("data-type","0");
                    $("#rebate_switch_title").text(_("白钻倍率")+"：");
                }else if(rebate_type==0){
                    $(this).attr("data-type","1");
                    $("#rebate_switch_title").text(_("白钻加点")+"：");
                }
            });

            //切换空托倍率 优惠  添加和编辑
            $("#inlaysbate_switch").on("click",function(){
                var inlaysbate_type=$(this).attr("data-type");
                if(inlaysbate_type == 0){
                    $(this).attr("data-type","1");
                    $("#inlaysbate_switch_title").text(_("空托优惠")+"：");
                    $("#add_inlaysRebate").hide();
                    $("#add_inlaysDiscounts").show();

                }else if(inlaysbate_type == 1){
                    $(this).attr("data-type","0");
                    $("#inlaysbate_switch_title").text(_("空托倍率")+"：");
                    $("#add_inlaysRebate").show();
                    $("#add_inlaysDiscounts").hide();
                }
            });

            $("#active_inlaysbate_switch").on('click',function(){
                var inlaysbate_type=$(this).attr("data-type");
                if(inlaysbate_type == 0){
                    $(this).attr("data-type","1");
                    $("#active_inlaysbate_switch_title").text(_("空托优惠")+"：");
                    $("#active_inlaysRebate").hide();
                    $("#active_inlaysDiscounts").show();

                }else if(inlaysbate_type == 1){
                    $(this).attr("data-type","0");
                    $("#active_inlaysbate_switch_title").text(_("空托倍率")+"：");
                    $("#active_inlaysRebate").show();
                    $("#active_inlaysDiscounts").hide();
                }
            })


            //批量修改供应商角色
            $("#role_btn").on("click",function(){
                $(".control_ul").hide();
                myApp.popup("#batch_RoleName_box");
            });
            //批量修改优惠
            $("#discounts_btn").on('click',function(){
                myApp.popup("#discounts_box");
            })
            //批量修改供应商输入验证
            var validate = $("#batch_RoleName_form").validate({
                debug: true, //调试模式取消submit的默认提交功能
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
                    self.batchSupplierRole();//客户充值
                },
                rules: {
                    RoleNames:"required",
                },
                messages: {
                    RoleNames: "",
                }
            });
            //批量修改优惠输入验证
            var validate = $("#discounts_form").validate({
                debug: true, //调试模式取消submit的默认提交功能
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
                    self.discountsSub();//客户充值
                },
                rules: {
                    RoleNames:"required",
                },
                messages: {
                    RoleNames: "",
                }
            });
            //新增编辑提交验证
            var aValidate = $("#form_data").validate({
                debug: true, //调试模式取消submit的默认提交功能
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
//              	self.addCustomer();
                    var add_Discounts=Number($("#add_Discounts").val());//优惠
                    if(add_Discounts =="" || add_Discounts>=0 && add_Discounts<=1){
                        self.addCustomer();//添加客户
                    }else{
                        alert(_("优惠的值只能输入0-1的数"));
                    }
                },
                rules: {
                    UserName: "required",
                    UserPassword: "required",
                    NickName: "required",
                    RealName: "required",
                    Mobile: "required",
                    SalesUserID: "required",
                    PurchaseUserID: "required",
                },
                messages: {
                    UserName: "",
                    UserPassword: "",
                    NickName: "",
                    RealName: "",
                    Mobile: "",
                    SalesUserID: "",
                    PurchaseUserID: "",

                }
            });
            //分销
            var validate = $("#_Dist").validate({
                debug: true, //调试模式取消submit的默认提交功能
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
                    self.DistCustomer();//分销客户
                },
                rules: {
                    CustomerKey: "required",
                    ValidDate:"required",
                },
                messages: {
                    CustomerKey:"",
                    ValidDate:"",
                }
            });

            //移交客户输入验证 id=_transfer
            var validate = $("#_transfer").validate({
                debug: true, //调试模式取消submit的默认提交功能
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
                    self.TransferCustomer();//转移客户
                },
                rules: {
                    SalesUserID: "required",
                },
                messages: {
                    SalesUserID:"",
                }
            });

            //帐号已注册
            jQuery.validator.addMethod("UserNameIsExist", function (value, element) {    //用jquery ajax的方法验证电话是不是已存在
                var flag = 1;
                $.ajax({
                    url: "/Customer/CustomerRegIsExist",//提交地址
                    type: "POST",//提交方式
                    data: "{'UserName':'" + $("#add_userName").val().trim() + "'}",
                    async: false,
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        var _result = eval('(' + result + ')');//eval()解析单个json对象
                        if (_result['msgcode'] == false) {
                            flag = 0;
                        }
                    },
                    error: function (err) {
                        myApp.alert("err:" + err);
                    }
                });
                if (flag == 1) {
                    return true;

                } else {
                    return false;
                }
            }, "已注册");//帐号已被注册

            //手机已注册
            jQuery.validator.addMethod("MobileIsExist", function (value, element) {    //用jquery ajax的方法验证电话是不是已存在
                var flag = 1;
                $.ajax({
                    url: "/Customer/CustomerRegIsExist",//提交地址
                    type: "POST",//提交方式
                    data: "{'Mobile':'" + $("#add_mobile").val().trim() + "'}",
                    async: false,
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        var _result = eval('(' + result + ')');//eval()解析单个json对象
                        if (_result['msgcode'] == false) {
                            flag = 0;
                        }
                    },
                    error: function (err) {
                        myApp.alert("err:" + err);
                    }
                });
                if (flag == 1) {
                    return true;

                } else {
                    return false;
                }
            }, "已注册");//手机已被注册

            //昵称已注册
            jQuery.validator.addMethod("NickNameIsExist", function (value, element) {    //用jquery ajax的方法验证电话是不是已存在
                var flag = 1;
                $.ajax({
                    url: "/Customer/CustomerRegIsExist",//提交地址
                    type: "POST",//提交方式
                    data: "{'NickName':'" + $("#add_nickName").val() + "'}",
                    async: false,
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        var _result = eval('(' + result + ')');//eval()解析单个json对象
                        if (_result['msgcode'] == false) {
                            flag = 0;
                        }
                    },
                    error: function (err) {
                        myApp.alert("err:" + err);
                    }
                });
                if (flag == 1) {
                    return true;

                } else {
                    return false;
                }
            }, "已注册");//昵称已被注册

            //申请提现输入验证 12-13
            var validate = $("._cash").validate({
                debug: true, //调试模式取消submit的默认提交功能
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应
                onkeyup: false,
                errorPlacement: function (error, element) {
                    if (element.is(":radio"))
                        error.appendTo(element.parent().parent());
                    else if (element.is(":checkbox"))
                        error.appendTo(element.parent().parent());
                    else
                        error.appendTo(element.parent().next());
                },//调radio
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
                    self.ApplyCash();//添加流水
                },
                rules: {
                    Amount: "required",
                    Balance: "required",
                    Remarks: "required",
                    Account: "required",
                    ArrivalTime: "required",
                },
                messages: {
                    Amount: "",
                    Remarks: "",
                    Balance: "",
                    Account: _("账户必选"),
                    ArrivalTime: "",
                }
            });

            //余额调节输入验证 12-27
            var validate = $("._adjust").validate({
                debug: true, //调试模式取消submit的默认提交功能
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
                    self.AdjustBalance();//调节余额
                },
                rules: {
                    // Amount: "required",
                    // USDAmount: "required",
                },
                messages: {
                    // Amount: "",
                    // USDAmount: "",
                }
            });

            //审核客户输入验证 class=activecustomer_form
            var validate = $("#activecustomer_form").validate({
                debug: true, //调试模式取消submit的默认提交功能
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form

                    var form_Discounts=Number($("#form_Discounts").val());//优惠
                    if(form_Discounts =="" || form_Discounts>=0 && form_Discounts<=1){
                        self.ActiveCustomer();//审核客户
                    }else{
                        alert(_("优惠的值只能输入0-1的数"));
                    }
                },
                rules: {
                    UserName: "required",
                    NickName: "required",
                    RealName:"required",
                    SalesUserID:"required",
                    PurchaseUserID:"required",
                    Rebate:"required",
                    FancyRebate:"required",
                },
                messages: {
                    UserName: "",
                    NickName:  "",
                    RealName:  "",
                    SalesUserID:  "",
                    PurchaseUserID: "",
                    Rebate: "",
                    FancyRebate: "",
                }
            });


        },
        //批量修改供应商角色
        batchSupplierRole:function(){
            var self=this;
            //OrderIDs值组装 _orderIDs="232,324"
            var customerlistCb = $("#stock_body .check_rel span.selected");//checked的
            var _customerIDs = [];
            for (var i = 0; i < customerlistCb.length; i++) {
                _customerIDs.push(customerlistCb[i].lang);
            }
            var submitJson={};
            var roleVal=$("#batch_RoleName").val();
            // submitJson.RoleNames=roleVal.join(",");
            var roleVal=$('#control_id_role input[name="control_id"]:checked').size();

            if(roleVal>0){
                var idList=[];
                $('#control_id_role input[name="control_id"]:checked').each(function (i) {
                    idList.push($(this).val());
                });
                submitJson.RoleNames=idList.join(",");
            }else{
                submitJson.RoleNames="";
            }
            submitJson.CustomerIDs=_customerIDs;
            $.ajax({
                url:"/team/BatchUpdateCustomerRoleNameByCustomerIDs",
                type:"POST",
                data:JSON.stringify(submitJson),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var res=eval('('+result+')');
                    if(res.msgcode==true){
                        toast(res.msginfo);
                        $("#batch_RoleName_box").hide();
                        getCustomer();
                        self.getSupplierRoles();
                    }else{
                        myApp.alert(res.msginfo);
                    }
                }
            });
        },

        discountsSub:function(){
            var self=this;
            //OrderIDs值组装 _orderIDs="232,324"
            var customerlistCb = $("#stock_body .check_rel span.selected");//checked的
            var _customerIDs = [];
            for (var i = 0; i < customerlistCb.length; i++) {
                _customerIDs.push(customerlistCb[i].lang);
            }
            var submitJson={};
            if($("#_discounts").val()>0){
                submitJson.Discounts=$("#_discounts").val();
            }else{
                myApp.alert('优惠值需大于0');
                return;
            }
            submitJson.CustomerIDs=_customerIDs;
            $.ajax({
                url:"/team/UpdateCustomerDiscounts",
                type:"POST",
                data:JSON.stringify(submitJson),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var res=eval('('+result+')');
                    if(res.msgcode==true){
                        toast(res.msginfo);
                        $("#discounts_box").hide();
                        getCustomer();
                    }else{
                        myApp.alert(res.msginfo);
                    }
                }
            });
        },
        //绑定权限
        bindPower:function(id){
//			myApp.popup("#power_box");
            $.ajax({
                url: "/team/GetCustomerRights",//提交地址
                type: "POST",//提交方式
                data: "{'CustomerID':'" + id + "'}",
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');
                    if(_result.msgcode==true){
                        var data=_result.msginfo;
                        var powerVal=data.Control_Column_Ids;
                        if(powerVal!=""){
                            var power=powerVal.split(",");
                            for(var i=0;i<power.length;i++){

                                for(var j=0;j<$("#power_label_box input[type=checkbox]").length;j++){

                                    if($("#power_label_box input[type=checkbox]").eq(j).val()==power[i]){
                                        $("#power_label_box input[type=checkbox]").eq(j).prop("checked",true);
                                        $("#form_power_label_box input[type=checkbox]").eq(j).prop("checked",true);
                                    }

                                }


                            }
                        }

                    }else{
                        myApp.alert(_(_result.msginfo));
                    }
                }
            });
        },

        //绑定权限产品
        bindPowerNew:function(id){
            myApp.popup(".power_form_box")
            $.ajax({
                url: "/team/GetCustomerRights",//提交地址
                type: "POST",//提交方式
                data: "{'CustomerID':'" + id + "'}",
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');
                    if(_result.msgcode==true){
                        var data=_result.msginfo;
                        var powerVal=data.Control_Column_Ids;
                        if(powerVal!=""){
                            var power=powerVal.split("|");
                            for(var i=0;i<power.length;i++){
                               var powerdata=power[i].split(',');
                                for(var j=0;j<powerdata.length;j++){
                                    $("#form_data_power input[value='"+powerdata[j]+"']").prop('checked',true);
                                }
                            }
                        }

                    }else{
                        myApp.alert(_(_result.msginfo));
                    }
                }
            });
        },

        //修改供应商
        stringInput:function(id) {
            var arr=[];
            $(''+id+' input[name="control_id"]:checked').each(function (i) {
                arr.push($(this).attr('data-names'));
            });
            var tt= $(id).children().clone();
            $(id).html(arr.join(',')).append(tt)
        },
        //客户权限
//		powerCustomer:function(){
//			var self=this;
//			var submitJson={};
//			var inventorylistCb = $("#power_label_box input[type=checkbox]:checked"); //checked的
//			var IDs = "";
//			for(var i = 0; i < inventorylistCb.length; i++) {
//				IDs +=  inventorylistCb[i].value+",";
//			}
//			IDs = IDs.substring(0, IDs.lastIndexOf(','));
//			submitJson.Control_Column_Ids=IDs;
//			submitJson.CustomerID=$("#power_CustomerID").val();
//			$.ajax({
//              url: "/team/SubmitCustomerRights",//提交地址
//              type: "POST",//提交方式
//              data: JSON.stringify(submitJson),
//              contentType: "application/json; charset=utf-8",
//              success: function (result) {
//                  var _result = eval('(' + result + ')');
//                  if(_result.msgcode==true){
//                  	$("#power_box").hide();
//                  	myApp.alert(_(_result.msginfo));
//                  	self.getCustomer();
//                  }else{
//                  	myApp.alert(_(_result.msginfo));
//                  }
//              }
//          });
//		},
        //新增客户
        addCustomer:function(){
            var self=this;
            myApp.showPreloader(_('正在提交中，请稍等...'));
            var datas={};
            var requestCustomer = $('#form_data').serializeArray().reduce(function(result, item){
                if(item.name=='GoldPrice'||item.name=='SideLaborFee'||item.name=='LaborFee'||item.name=='Wastage'||item.name=='SidePrice'||item.name=='Insurance'){
                    datas[item.name]= item.value;
                }else {
                    result[item.name] = item.value;
                }
                return result;
            }, {})//把提交的数据转为JSON格式

            //空托start
            if($('#inlaysbate_switch').attr('data-type')==1){
                requestCustomer.IsSetInlaySettings=1;
                requestCustomer.InlaySettingsRebate=JSON.stringify(datas);
            }else {
                requestCustomer.IsSetInlaySettings=0
            }
            //空托end
            requestCustomer.UserName=$("#add_userName").val();
            requestCustomer.IsRebate=$("#rebate_switch").attr("data-type");

            var roleVal=$('#control_id input[name="control_id"]:checked').size();
            if(roleVal>0){
                var idList=[];
                $('#control_id input[name="control_id"]:checked').each(function (i) {
                    idList.push($(this).val());
                });
                requestCustomer.RoleNames=idList.join(",");
            }else{
                requestCustomer.RoleNames="";
            }
            if(EDITMODE){
                var inventorylistCb = $("#form_power_label_box input[type=checkbox]:checked"); //checked的
                var IDs = "";
                for(var i = 0; i < inventorylistCb.length; i++) {
                    IDs +=  inventorylistCb[i].value+",";
                }
                IDs = IDs.substring(0, IDs.lastIndexOf(','));
                // requestCustomer.Control_Column_Ids=IDs;
                var submitUrl="/Team/EditCustomer";
            }else{
                var submitUrl="/Team/AddCustomer";
            }

            $.ajax({
                url: submitUrl,//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(requestCustomer),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
                    myApp.hidePreloader();
                    if(_result.msgcode == true){
                        myApp.alert(_(_result.msginfo),function(){
                            getCustomer();
                            $(".customer_form_box").hide();
                        });
                    }else{
                        myApp.alert(_(_result.msginfo));
                    }
                }
            });
        },
        //获取供应商角色
        getSupplierRoles:function(){
            $.ajax({
                type:"POST",
                url:"/team/QuerySupplierRole",
                success:function(result){
                    var res=eval('('+result+')');
                    if(res.msgcode==true){

                        var ulHtml='<ul class="control_ul" id="id_ul" style="display: none;">';
                        var liHtml='';

                        var da={'RoleName':'','GoodsType':'','children':[]};
                        var da1={'RoleName':'','GoodsType':'','children':[]};
                        var da2={'RoleName':'','GoodsType':'','children':[]};
                        var da3={'RoleName':'','GoodsType':'','children':[]};
                        var da4={'RoleName':'','GoodsType':'','children':[]};
                        var da5={'RoleName':'','GoodsType':'','children':[]};
                        var da6={'RoleName':'','GoodsType':'','children':[]};

                        var arrs=[];
                        for(var i=0;i<res.msginfo.length;i++){
                            var data=res.msginfo[i];
                            if(data.GoodsType==1 && isDia=='true'){
                                da.RoleName='裸钻(全选)';
                                da.GoodsType=data.GoodsType;
                                da.children.push({'RoleName':data.RoleName,'ID':data.ID,'GoodsType':data.GoodsType});
                            };
                            if(data.GoodsType== 2&& isParcel=='true'){
                                da1.RoleName='统包(全选)';
                                da1.GoodsType=data.GoodsType;
                                da1.children.push({'RoleName':data.RoleName,'ID':data.ID,'GoodsType':data.GoodsType});
                            }
                            if(data.GoodsType==3 && isRing=='true'){
                                da2.RoleName='成品(全选)';
                                da2.GoodsType=data.GoodsType;
                                da2.children.push({'RoleName':data.RoleName,'ID':data.ID,'GoodsType':data.GoodsType});
                            }
                            if(data.GoodsType==4 && isGem == 'true'){
                                da3.RoleName='彩宝(全选)';
                                da3.GoodsType=data.GoodsType;
                                da3.children.push({'RoleName':data.RoleName,'ID':data.ID,'GoodsType':data.GoodsType});
                            }
                            if(data.GoodsType==5 && isEmerald == 'true'){
                                da4.RoleName='翡翠(全选)';
                                da4.GoodsType=data.GoodsType;
                                da4.children.push({'RoleName':data.RoleName,'ID':data.ID,'GoodsType':data.GoodsType});
                            }
                            if(data.GoodsType==6 && isPrimeGold == 'true'){
                                da5.RoleName='素金(全选)';
                                da5.GoodsType=data.GoodsType;
                                da5.children.push({'RoleName':data.RoleName,'ID':data.ID,'GoodsType':data.GoodsType});
                            }
                            if(data.GoodsType==7 && isInlaySettings == 'true'){
                                da5.RoleName='空托(全选)';
                                da5.GoodsType=data.GoodsType;
                                da5.children.push({'RoleName':data.RoleName,'ID':data.ID,'GoodsType':data.GoodsType});
                            }
                        }
                        if(da.RoleName){
                            arrs.push(da)
                        }
                        if(da1.RoleName){
                            arrs.push(da1)
                        }
                        if(da2.RoleName){
                            arrs.push(da2)
                        }
                        if(da3.RoleName){
                            arrs.push(da3)
                        }
                        if(da4.RoleName){
                            arrs.push(da4)
                        }
                        if(da5.RoleName){
                            arrs.push(da5)
                        }
                        if(da6.RoleName){
                            arrs.push(da6)
                        }

                        if(arrs.length>0){
                            for(var j=0;j<arrs.length;j++){
                                liHtml+='<li class="control_li is_parent_li">' +
                                    '<input type="checkbox" class="is_parent check" data-lant="'+arrs[j].GoodsType+'" name="name">' +
                                    '<label>'+arrs[j].RoleName+'</label>' +
                                    '</li>';
                                for(var g=0;g<arrs[j].children.length;g++){
                                    liHtml+='<li class="control_li check_child_li" style="padding-left: 30px">' +
                                        '<input type="checkbox" class="check_child" data-lant="'+arrs[j].children[g].GoodsType+'" id="'+arrs[j].children[g].ID+'" data-names="'+arrs[j].children[g].RoleName+'"' +
                                        ' value="'+arrs[j].children[g].ID+'" name="control_id">' +
                                        '<label style="text-align: left" for="'+arrs[j].children[g].ID+'">'+arrs[j].children[g].RoleName+'</label>' +
                                        '</li>';
                                }

                            }
                        }

                        ulHtml+=liHtml+'</ul>';
                        $('#control_id').html(ulHtml)
                        $('#control_id_role').html(ulHtml)


                        // var $html=[];
                        // for(var i=0;i<res.msginfo.length;i++){
                        //     var data=res.msginfo[i];
                        //     $html.push(
                        //         '<option value='+data.RoleName+'>'+data.RoleName+'</option>'
                        //     );
                        // }
                        // $("#form_RoleName,#batch_RoleName").html($html);
                        // //下拉多选
                        // $("#batch_RoleName").multipleSelect({
                        //     placeholder: _("请选择"),
                        //     selectAllText: _("全选")
                        //     // filter: true
                        // });
                        // $('#form_RoleName').multipleSelect({
                        //     placeholder: _("请选择"),
                        //     selectAllText: _("全选")
                        //     // filter: true
                        // });
                    }else{
                        // $("#form_RoleName,#batch_RoleName").html("");
                        //alertMsgBox(res.msginfo);
                    }
                }
            });
        },
        //编辑时绑定数据
        bindData:function(ID,form_data){
           // myApp.showIndicator();//显示加载中
            $("#reset_btn").hide();
            var self=this;
            var submitJson={};
            submitJson.CustomerID=ID;

            $.ajax({
                url:'/Customer/GetCustomerInfo',
                type:'POST',
                data: JSON.stringify(submitJson),
                dataType:'JSON',
                contentType: "application/json; charset=utf8",
                success:function(result){
                    var data=eval('(' + result + ')')
                    $("#"+form_data).setForm(data);//帮数据
                    $("#id_input").prop({"name":"CustomerID","value":data.CustomerID});//ID
                    $("#combo_sales [value='" + data.SalesUserID + "']").prop("selected", true);//下拉框
                    $("#active_sales [value='" + data.SalesUserID + "']").prop("selected", true);//下拉框
                    $("#combo_purchases [value='" + data.PurchaseUserID + "']").prop("selected", true);//下拉框
                    if (data.RoleNames && data.RoleNames != "" && data.RoleNames!=null) {
                        var da=data.RoleNames.split(',');
                        for (var j=0;j<da.length;j++){
                            $('#control_id input[value="'+da[j]+'"]').prop('checked',true)
                        }

                        $('#control_id input[name="control_id"]:checked').each(function (i) {
                            var type=$(this).attr('data-lant');
                            var isChangeLen = $('#control_id .check_child_li input[data-lant="'+type+'"]:checked').size();
                            var isChangeLenNo = $('#control_id .check_child_li input[data-lant="'+type+'"]').size();
                            if(isChangeLen==isChangeLenNo){
                                $('#control_id .is_parent_li').find('input[data-lant="'+type+'"]').prop('checked',true);
                            }else {
                                $('#control_id .is_parent_li').find('input[data-lant="'+type+'"]').removeAttr("checked");
                            }
                        });
                        self.stringInput('#control_id');
                        // $('#form_RoleName').multipleSelect("setSelects", []); //清空
                        // $('#form_RoleName').multipleSelect("setSelects", data.RoleNames.split(',')); //设置选中
                    }
                    if(form_data=="form_data"){
                        // self.bindPower(ID);
                        if(data.IsRebate==1){//白钻加点
                            $(this).attr("data-type","1");
                            $("#rebate_switch_title").text(_("白钻加点")+"：");
                        }else{//白钻倍率
                            $(this).attr("data-type","0");
                            $("#rebate_switch_title").text(_("白钻倍率")+"：");
                        }
                    }

                    $("#inlaysbate_switch").attr("data-type",data.IsSetInlaySettings);
                    if(data.IsSetInlaySettings==1){
                        $("#inlaysbate_switch_title").text("空托优惠")

                        $("#add_inlaysRebate").hide();
                        $("#add_inlaysDiscounts").show();

                        var data_parse=JSON.parse(data.InlaySettingsRebate);
                        $("#goldPrice").val(data_parse.GoldPrice);
                        $("#sideLaborFee").val(data_parse.SideLaborFee);
                        $("#laborFee").val(data_parse.LaborFee);
                        $("#wastage").val(data_parse.Wastage);
                        $("#sidePrice").val(data_parse.SidePrice);
                        $("#insurance").val(data_parse.Insurance);

                    }else{
                        $("#inlaysbate_switch_title").text("空托倍率")
                        $("#add_inlaysRebate").show();
                        $("#add_inlaysDiscounts").hide();
                    }

                    myApp.hideIndicator();//隐藏加载中
                }
            });
        },
        //业务列表
        GetSale:function(lib){
            var request = {};
            if(RoleID==3 || RoleID== 6){
                request.UserID = UserID;
            }
            request.SysStatus =1;
            var options_sales = "";
            options_sales += '<option value="">'+_("--选择业务--")+'</option>';
            if(sales==""){
                $.ajax({
                    url: "/Team/GetSaleList",//提交地址
                    type: "POST",//提交方式
                    data: JSON.stringify(request),
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        var _result = eval('(' + result + ')');//eval()解析单个json对象
                        if(_result.msgcode == false){
                            //暂无业务
                            options_sales += '<option value="">'+_(_result.msginfo)+'</option>';
                            $("#"+lib).html("");
                            $("#"+lib).html(options_sales);

                        }else{
                            //有业务
                            sales=_result;
                            for (var i = 0; i < _result.length; i++) {
                                options_sales += '<option value="' + _result[i].UserID + '"  >' + _result[i].RealName + '</option>';
                            }
                            $("#"+lib).html("");
                            $("#"+lib).html(options_sales);
                        }
                    }
                });
            }else{
                var _result = sales ;//eval('(' + sales + ')');//eval()解析单个json对象
                for (var i = 0; i < _result.length; i++) {
                    options_sales += '<option value="' + _result[i].UserID + '"  >' + _result[i].RealName + '</option>';
                }
                $("#"+lib).html("");
                $("#"+lib).html(options_sales);
            }
        },
        //申请Tx提现账户列表
        TxAccountLoad:function(val) {

            var requestAccount = {};
            requestAccount.Status = 1;//启用1
            requestAccount.Type = '2,3';

            if(val==0){//提现   显示和隐藏银行
                if(CurrentRMB==true && CurrentUSD==true){
                    //requestAccount.Currency = 0;//币种 1.人民币 2.美元
                }else if(CurrentRMB==true && CurrentUSD==false){
                    requestAccount.Currency = 1;//币种 1.人民币 2.美元
                }else if(CurrentUSD==true && CurrentRMB==false){
                    requestAccount.Currency = 2;//币种 1.人民币 2.美元
                }
            }else{
                requestAccount.Currency=val;
            }

            $.ajax({
                url: "/Team/GetBankList",//提交地址
                type: "POST",//提交方式
                async: false, //异步 9-27
                data: JSON.stringify(requestAccount),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象

                    if (_result.msgcode == false) {
                        var options = "";
                        options += '<lable>' + _(_result.msginfo) + '</label>';
                        $("#_bankID2").html("");//账户下拉
                        $("#_bankID2").html(options);
                    } else {
                        var options = "";
                        for (var i = 0; i < _result.length; i++) {
                            options += '<span class="bank_span"><input type="radio"  onclick="radioBtn(this,'+_result[i].Currency+')" name="Account" value="' + _result[i].BankID + '" id="txaccout' + i + '" /><label for="txaccout' + i + '">' + _result[i].BankName + '</label></span>';
                        }
                        $("#_bankID2").html("");//账户下拉
                        $("#_bankID2").html(options);
                    }
                }
            });
        },

        //确定余额调节
        AdjustBalance:function(){
            var self=this;
            myApp.confirm(_("确定要调节客户余额吗？"),function(){
                var requestBal = {};
                requestBal.CustomerID = $("#adjust_cuID").val();//客户ID
                requestBal.Balance = $("#adjustamount").val();
                requestBal.USDBalance = $("#adjustusdamount").val();

                $.ajax({
                    url: "/Team/EditCustomer",//提交地址
                    type: "POST",//提交方式
                    data: JSON.stringify(requestBal),
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        var _result = eval('(' + result + ')');//eval()解析单个json对象
                        if (_result.msgcode == true) {
                            myApp.alert(_(_result.msginfo));
                            $(".Adjust_box input[type=reset]").trigger("click");//清空form数据 12-13
//		                    $(".Adjust_box").hide();//关闭调节框
                            myApp.closeModal(".Adjust_box");
                            getCustomer();
                        } else {
                            myApp.alert(_(_result.msginfo));//失败
                        }
                    }
                });
            });
        },

        //确定申请余额提现
        ApplyCash:function(){
            var self=this;
            //优化01-11
            var requestFlow = {};
            requestFlow.CustomerID = $("#_customID").val();//客户ID
            requestFlow.ApplyID = $.cookie("UserID");
            requestFlow.Remarks = $("#tremarks").val();
            requestFlow.Amount = $("#tamount").val();//提现金额
            requestFlow.Balance= $("#_bala").val();//当前余额
            requestFlow.USDBalance=$("#_usdbala").val();
            requestFlow.ArrivalTime = $("#tarrivalTime").val();
            requestFlow.Type = 2; //定金1（收入） 提现2（支出）
            requestFlow.Abstract = 5;//操作类型(摘要) 1.出货全款 2.定货款/尾款 5提现
            // requestFlow.Currency = 1;//币种 1.人民币 2.美元
            requestFlow.Currency= $("#_bala_hidden").val();//币种 1.人民币 2.美元
            // requestFlow.Currency =$("#_bankID2 input[type=radio]:checked").attr("lang");//币种 1.人民币 2.美元
            requestFlow.Status = 0;//0待审核 1已审核 -1 已作废
            //requestFlow.Account =$('input:radio[name="Account"]:checked').val();
            requestFlow.Account =$('#_bankID2 input:radio[name="Account"]:checked').val(); //动态radio 12-21
            $.ajax({
                url: "/Team/AddFlow",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(requestFlow),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
                    if (_result.msgcode == true) {
                        myApp.closeModal(".Cash_box");
                        $(".Cash_box input[type=reset]").trigger("click");//清空form数据 12-13
                        myApp.alert(_(_result.msginfo),function(){
                            if(APP){

                            }else{
                                //location.href = "/team/apply";//申请 12-9
                            }
                        });
                        getCustomer();
                    } else {
                        myApp.alert(_(_result.msginfo));//失败
                    }

                }
            });
        },

        //采购列表
        GetPurchase:function(lib){
            var options_purchases = "";
            options_purchases += '<option value="">'+_("采购")+'</option>';
            if(purchases==""){
                $.ajax({
                    url: "/Team/GetPurchaseList",//提交地址
                    type: "POST",//提交方式
                    data: "{'SysStatus':'" + 1 + "'}",
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        var _result = eval('(' + result + ')');//eval()解析单个json对象
                        if(_result.msgcode == false){
                            options_purchases += '<option value="">'+_(_result.msginfo)+'</option>';
                            $("#"+lib).html("");
                            $("#"+lib).html(options_purchases);
                        }else{
                            for (var i = 0; i < _result.length; i++) {
                                options_purchases += '<option value="' + _result[i].UserID + '"  >' + _result[i].RealName + '</option>';
                            }
                            $("#"+lib).html("");
                            $("#"+lib).html(options_purchases);
                        }
                    }
                });
            }else{
                var _result = purchases ;//eval('(' + sales + ')');//eval()解析单个json对象
                for (var i = 0; i < _result.length; i++) {
                    options_purchases += '<option value="' + _result[i].UserID + '"  >' + _result[i].RealName + '</option>';
                }
                $("#"+lib).html("");
                $("#"+lib).html(options_purchases);
            }
        },
        //审核
        ActiveCustomer:function(){
            var self=this;
            //客户权限开始
            var inventorylistCb = $("#power_label_box input[type=checkbox]:checked"); //checked的
            var IDs = "";
            for(var i = 0; i < inventorylistCb.length; i++) {
                IDs +=  inventorylistCb[i].value+",";
            }
            IDs = IDs.substring(0, IDs.lastIndexOf(','));
            //客户权限结束

            var datas={};
            var requestCustomer = $('#activecustomer_form').serializeArray().reduce(function(result, item){
                if(item.name=='GoldPrice'||item.name=='SideLaborFee'||item.name=='LaborFee'||item.name=='Wastage'||item.name=='SidePrice'||item.name=='Insurance'){
                    datas[item.name]= item.value;
                }else {
                    result[item.name] = item.value;
                }
                return result;
            }, {})//把提交的数据转为JSON格式

            //空托start
            if($('#inlaysbate_switch').attr('data-type')==1){
                requestCustomer.IsSetInlaySettings=1;
                requestCustomer.InlaySettingsRebate=JSON.stringify(datas);
            }else {
                requestCustomer.IsSetInlaySettings=0
            }
            //空托end

            // var requestCustomer = {};
            // requestCustomer.CustomerID = $("#active_customerID").val();
            // requestCustomer.UserName = $("#active_userName").val();
            // requestCustomer.CompanyName = $("#active_companyName").val();
            // requestCustomer.NickName = $("#active_nickName").val();
            // requestCustomer.Introducer = $("#active_introducer").val();
            // requestCustomer.RealName = $("#active_realName").val();
            // requestCustomer.SysStatus = $("#active_sysStatus option:checked").val();
            // requestCustomer.SalesUserID = $("#active_sales option:checked").val();
            // requestCustomer.PurchaseUserID = $("#active_purchases option:checked").val();
            // requestCustomer.Rebate = $("#active_rebate").val();
            // requestCustomer.FancyRebate = $("#active_fancyRebate").val();
            // requestCustomer.Mobile = $("#active_mobile").val();
            // requestCustomer.Control_Column_Ids=IDs;//客户权限id集合
            $.ajax({
                url: "/Team/ActiveCustomer",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(requestCustomer),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
                    myApp.alert(_(_result["msginfo"]),function(){
                        myApp.closeModal('.popup_Active_box');
                        if(_result.msginfo == "审核成功"){
                            $("#form_data_power").attr('data-id',requestCustomer.CustomerID);
                            self.bindPowerNew(requestCustomer.CustomerID);
                        }
                        getCustomer();
                    });
                }
            });
        },

        //分销
        DistCustomer: function (me){
            var self=this;
            //CustomerID值组装
            var customerlistCb = $("#stock_body .check_rel span.selected");//checked的
            var _customerIDs = "";
            for (var i = 0; i < customerlistCb.length; i++) {
                if (i == 0)
                    _customerIDs += customerlistCb[i].lang;
                else
                    _customerIDs += "," + customerlistCb[i].lang;
            }
            var requestDist = {};
            requestDist.CustomerID = _customerIDs;
            requestDist.CustomerKey = $("#_customerkey").val().trim();
            requestDist.ValidDate = $("#_validDate").val();
            $.ajax({
                url: "/Customer/EditCustomer",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(requestDist),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
                    myApp.alert(_(_result.msginfo),function(){
                        myApp.closeModal(".popup_Dist_box");
//	                	$(".Dist_box").hide();
                        getCustomer();//获取列表
                    });
                }
            });

        },
        //移交客户 9-24
        TransferCustomer:function(){
            var self=this;
            //OrderIDs值组装 _orderIDs="232,324"
            var customerlistCb = $("#stock_body .check_rel span.selected");//checked的
            var _customerIDs = "";
            for (var i = 0; i < customerlistCb.length; i++) {
                if (i == 0)
                    _customerIDs += customerlistCb[i].lang;
                else
                    _customerIDs += "," + customerlistCb[i].lang;
            }
            $.ajax({
                url: "/Team/ModifySalesUserID",//提交地址
                type: "POST",//提交方式
                data: "{'CustomerIDs':'" + _customerIDs + "','SalesUserID':'" + $("#_salesUserIDs option:checked").val() + "'}",  //$("#test option:selected")
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
                    myApp.alert(_result["msginfo"],function(){
                        myApp.closeModal(".popup_ModifySalesUserID_box");
//	            		 $(".ModifySalesUserID_box").hide();
                        getCustomer();//获取列表
                    });

                }
            });
        },



    }
    customer.init();
})();

//选择银行
function radioBtn(me,type) {
    //type 2 美元 1 人民币
    if(type==2){
        // $('#_bala').val(balanceDate.USDBalance);
        $('#_bala_hidden').val('2');
    }else {
        // $('#_bala').val(balanceDate.Balance);
        $('#_bala_hidden').val('1');
    }
}

//获取参数
function getParamer(){

    var requestCustomer={};

    // if(RoleID != 1)
    // {
    //     requestCustomer.SalesUserID =$.cookie("UserID");
    // }else{
    requestCustomer.SalesUserID = $("#_salesUserID").val();
    // }

    requestCustomer.PurchaseUserID = $("#_purchaseUserID").val();

    if($.cookie("_customer_statu_c")){
        requestCustomer.SysStatus=2;
        $("#_sysStatus").val(2);
        $.cookie("_customer_statu_c","",-1);
    }


    requestCustomer.UserName =$.trim($("#_userName").val());

    requestCustomer.CompanyName = $.trim($("#_companyName").val());
    //昵称cookie 订单页面传来的_nick
    if($.cookie("_nick")){
        $("#_nickName").val($.cookie("_nick"));
        $.cookie("_nick","",-1);
    }

    //名字cookie 充值页面传来的_nick2
    if($.cookie("_nick2")){
        $("#_customerRealName").val($.cookie("_nick2"));//真名
        $.cookie("_nick2","",-1);
    }


    requestCustomer.NickName = $.trim($("#_nickName").val());
    requestCustomer.RealName = $.trim($("#_customerRealName").val());//真名

    requestCustomer.Mobile = $.trim($("#_mobile").val());
    return requestCustomer;
}
//客户状态格式化
function sysStatusFormat(sysStatusValue) {
    if (sysStatusValue == -1) {
        return _("已删");
    } else if (sysStatusValue == 0) {
        return _("禁用");
    } else if (sysStatusValue == 2) {
        return _("待审");
    } else if(sysStatusValue == 1){
        return _("正常");
    }
    return sysStatusValue;
}
//日期时间格式化 03-09 dateTimeValue
function DateTimeHandler(dateTimeValue) {
    if (dateTimeValue != null && dateTimeValue != "") {
        var timeStr = dateTimeValue.replace('T', ' ').replace(/-/g, '/'); //兼容firefox
        var hisTime = new Date(timeStr).getTime();
        if (!hisTime) { //数据库中可能为unicode时间
            timeStr = eval(dateTimeValue.replace(/\/(Date\([0-9-]+\))\//gi, 'new $1'));
            hisTime = new Date(timeStr).getTime();
        }
        var now = new Date().getTime(),
            diffValue = now - hisTime,
            result = '',
            minute = 1000 * 60,
            hour = minute * 60,
            day = hour * 24,
            halfamonth = day * 15,
            month = day * 30,
            year = month * 12,

            _year = diffValue / year,
            _month = diffValue / month,
            _week = diffValue / (7 * day),
            _day = diffValue / day,
            _hour = diffValue / hour,
            _min = diffValue / minute;

        if (_year >= 1) result = parseInt(_year) + _("年前");
        else if (_month >= 1) result = parseInt(_month) + _("月前");
        else if (_week >= 1) result = parseInt(_week) + _("周前");
        else if (_day >= 1) result = parseInt(_day) + _("天前");
        else if (_hour >= 1) result = parseInt(_hour) + _("小时前");
        else if (_min >= 1) result = parseInt(_min) + _("分钟前");
        else result = _("刚刚");
        return result;
    } else {
        return '';
    }
}

//排序用的
function sort_startSearch(p) {
    getCustomer(p);
}

//获取客户列表
function getCustomer(p){
   // myApp.showIndicator();//显示加载中
    // var requestCustomer =getParamer();
    var requestCustomer;
    if(p){
        requestCustomer=p;
    }else{
        requestCustomer =getParamer(requestCustomer);
    }
    requestCustomer.PageIndex="1";
    requestCustomer.PageSize="500";
    requestCustomer.SysStatus=$("#_sysStatus ul li.add_blue").attr("data-value");
    requestCustomer.UserID=UserID;
    $.ajax({
        url: "/Team/GetCustomers",//提交地址
        type: "POST",//提交方式
        data: JSON.stringify(requestCustomer),
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            BindingData(result, $("#product_table tbody"));//绑定数据
            clearBtn();
            var _result = eval('(' + result + ')');
            myApp.hideIndicator();//隐藏加载中
            $("#th_check_all").find('span').removeClass("selected");
            getPengdingCount();
        }
    });
}
//待审数目
function getPengdingCount(){
    var requestCustomer={};
    requestCustomer.PageIndex="1";
    requestCustomer.PageSize="500";
    requestCustomer.SysStatus=2;
    requestCustomer.UserID=UserID;
    $.ajax({
        url: "/Team/GetCustomers",//提交地址
        type: "POST",//提交方式
        data: JSON.stringify(requestCustomer),
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            var _result = eval('(' + result + ')');
            if(requestCustomer.SysStatus==2){
                $("#wait_customer").html(_result.TotalCount);//客户总数
            }
        }
    });
}
function clearBtn(){
    $(".search_btn_b").css("background-color","#a1a1a1");
    $(".search_btn_b").attr("disabled",true);
}
//数据绑定
function BindingData(Datas, tableTbody) {
    var tableTbody = $("#stock_body");
    var _result = eval('(' + Datas + ')');//eval()解析单个json对象
    $("#_pageCount").html(_result.PageCount);//总页数 9-22
    $("#_pageSize").html(_result.PageSize);//每页总数
    $("#_totalCount").html(_result.TotalCount);//客户总数
    if(_result.msgcode == false){
        var tr = "";//单行
        var tds = "<td colspan='50' style='text-align:center;color:red'>" + _(_result.msginfo) + "</td>";// 多列合成一列并居中
        tr = "<tr>" + tds + "</tr>";//将多列加到一行
        tableTbody.html(tr);//加入到id为product_table的table的tbody中
        myApp.hideIndicator();//隐藏加载中

    }else{
        var _balance = 0;//总余额 12-1
        var _usdbalance = 0;//总余额 12-1
        _result = _result.Data;//object
        var trs = "";//多行数据
        for (var i = 0; i < _result.length; i++) {

            //本月销售额ThisConfirmPrice
            if(_result[i].ThisConfirmPrice!=null){
                _result[i].ThisConfirmPrice=String(_result[i].ThisConfirmPrice);
            }
            if(_result[i].ThisConfirmPrice){
                var arr=_result[i].ThisConfirmPrice.split('_');
                if(arr[0]>0&&arr[1]>0){
                    _result[i].ThisConfirmPrice='$'+formatUSDPrice(arr[0])+'/￥'+formatRMBPrice(arr[1])
                }else if(arr[0]>0){
                    _result[i].ThisConfirmPrice='$'+formatUSDPrice(arr[0])
                }else if(arr[1]>0){
                    _result[i].ThisConfirmPrice=formatRMBPrice(arr[1])
                }

            }

            //上月销售额
            if(_result[i].LastConfirmPrice!=null){
                _result[i].LastConfirmPrice=String(_result[i].LastConfirmPrice);
            }
            if(_result[i].LastConfirmPrice){
                var arr=_result[i].LastConfirmPrice.split('_');
                if(arr[0]>0&&arr[1]>0){
                    _result[i].LastConfirmPrice='$'+formatUSDPrice(arr[0])+'/￥'+formatRMBPrice(arr[1])
                }else if(arr[0]>0){
                    _result[i].LastConfirmPrice='$'+formatUSDPrice(arr[0])
                }else if(arr[1]>0){
                    _result[i].LastConfirmPrice=formatRMBPrice(arr[1])
                }

            }

            var tds = "";//多列
            var tr = "";//单行
            var tr_div = "";
//                  tds += "<td>" + (i + 1) + "</td>";
            tds += "<td class='check_rel'>"+
                "<div class='check_list_box'><span class='checkbox' name='checkbox' lang='" + _result[i].CustomerID + "'></span></div>";
//                  "<input type='checkbox'  value='check[i]' name='checkbox' lang='" + _result[i].CustomerID + "'/></td>";
            tds += "<td class='nickname'><a href='#' title='点击查看\"" + _result[i].NickName + "\"的订单' >" + _result[i].NickName + "</a></td>";
//                  tds += "<td class='nickname'><a href='#' title='点击查看\"" + _result[i].RealName + "\"的充值' >" + _result[i].RealName + "</a></td>";
            tds += "<td>" + partShowSubstring(_result[i].CompanyName) + "</td>";//公司全称
            tds += "<td class='cus_sysStatus' lang='"+ _result[i].SysStatus +"' data-balance='"+ _result[i].Balance +"'  data-USDBalance='"+ _result[i].USDBalance +"'>" + sysStatusFormat(_result[i].SysStatus) + "</td>";//状态
            tds += "<td>" + _result[i].LoginCount + "</td>";//次数
            tds += "<td class='nickname'>" + DateTimeHandler(_result[i].LastActiveTime) + "</td>";//上次
            tds += "<td>" + NullFormat(_result[i].SalesRealName) + "</td>"; //业务
            tds += "<td>" + NullFormat(_result[i].PurchaseRealName) + "</td>";//采购
            tds += "<td title='" + _result[i].ValidDate + "'>" + DateFormat(_result[i].ValidDate) + "</td>";//到期
            tr += "<tr class='data_tr'>" + tds + "</tr>";//将多列加到一行
            tr_div="<tr class='stock_detail'><td  colspan='9'>"+
                "<div class='detail_left' style='width:50%;'>"+
                "<i><b>"+_("帐号")+"：</b>"+_result[i].UserName+"</i>"+
                "<i><b>"+_("公司简称")+"：</b>"+_result[i].NickName+"</i>"+
                "<i><b>"+_("公司全称")+"：</b>"+_result[i].CompanyName+"</i>"+
                "<i><b>"+_("电话")+"：</b>" +NullFormat(_result[i].Mobile) + "</i>" +
                "<i><b class='custrom'>QQ：</b><span>" + NullFormat(_result[i].QQ) + "</span></i>"+
                "<i><b>"+_("网站")+"：</b>" + NullFormat(_result[i].Url) + "</i>"+
                "<i><b>IP：</b>" + NullFormat(_result[i].ActiveIP) + "</i>" +
                "<i><b>"+_("更新")+"：</b>" + DateTimeFormat(_result[i].UpdateTime) + "</i>"+
                "<i><b class='custrom'>"+_("创建")+"：</b>" + DateTimeFormat(_result[i].CreateTime) + "</i>" +
                "<i><b class='custrom'>"+_("负责人")+"：</b>" + NullFormat(_result[i].Principal) + "</i>" +
                "<i><b class='custrom'>"+_("经营")+"：</b>" + NullFormat(_result[i].Manager) + "</i>" +
                "</div>" +
                "<div class='detail_middle' style='width:50%;'>"+
                "<i><b>"+_("优惠")+"：</b>"+NullFormat(_result[i].Discounts)+"</i>"+
                "<i style='display:"+(isDia=='true'?'block':'none')+"'><b>"+_("白加")+"：</b>" + _result[i].Rebate + "</i>"+
                "<i style='display:"+(isDia=='true'?'block':'none')+"'><b>"+_("彩加")+"：</b>" +  _result[i].FancyRebate + "</i>"+
                "<i style='display:"+(isParcel=='true'?'block':'none')+"'><b>"+_("统包加")+"：</b>" +  _result[i].ParcelRebate + "</i>"+
                "<i style='display:"+(isRing=='true'?'block':'none')+"'><b>"+_("成品加")+"：</b>" +  _result[i].RingRebate + "</i>"+
                "<i style='display:"+(isGem=='true'?'block':'none')+"'><b>"+_("彩宝加")+"：</b>" +  _result[i].GemRebate + "</i>"+
                "<i style='display:"+(isEmerald=='true'?'block':'none')+"'><b>"+_("翡翠加")+"：</b>" +  _result[i].EmeraldRebate + "</i>"+
                "<i style='display:"+(isPrimeGold=='true'?'block':'none')+"'><b>"+_("素金加")+"：</b>" +  _result[i].PrimeGoldRebate + "</i>"+
                "<i class='ApplyFlow_Js CurrentRMB' data-id="+_result[i].CustomerID+"><a href='#'><b>￥"+_("余额")+"：</b>" + _result[i].Balance + "</a></i>"+
                "<i class='ApplyUSDFlow_Js CurrentUSD' data-id="+_result[i].CustomerID+"><a href='#'><b>$"+_("余额")+"：</b>" + _result[i].USDBalance + "</a></i>"+
                "<i class='CurrentRMB'><b>"+_("本月销售")+"￥：</b>" + _result[i].ThisConfirmPrice + "</i>"+
                "<i class='CurrentRMB'><b>"+_("上月销售")+"￥：</b>" + _result[i].LastConfirmPrice + "</i>"+
                "</div>";
            if (_result[i].SysStatus == -1) {
                tr_div+="</td></tr>";
            }else if(_result[i].SysStatus == 2){
                tr_div += "<div class='handle_div'>";//onclick='ActiveCustomer_Js(this)'
                if(originRoleID==1 || originRoleID==3 || originRoleID == 6 || menu_customer_power){
                    tr_div+="<div class='handle_div'><a href='#' class='power_btn' data-id='" + _result[i].CustomerID + "'>"+_("权限")+"</a>";
                }
                if(originRoleID==1 || originRoleID == 6 || menu_customer_auditing){
                    tr_div += "<a href='#' class='aduit_btn' data-id='" + _result[i].CustomerID + "'>"+_("审核")+"</a>"
                }
                tr_div+='</div></td></tr>';
            }
            //管理员1 财务2 可以余额调节 12-29
            else if(_result[i].SysStatus == 1 && (_result[i].Balance > 0 || _result[i].USDBalance > 0) && (RoleID == 1 || RoleID == 2)){
                tr_div += "<div class='handle_div'>";
                    //                      "<a href='#' class='edit_power_btn' data-id='" + _result[i].CustomerID + "'>"+_("权限")+"</a>"+
                if(originRoleID==1 || originRoleID==3 || originRoleID == 6 || menu_customer_power){
                    tr_div+="<a href='#' class='power_btn' data-id='" + _result[i].CustomerID + "'>"+_("权限")+"</a>";
                }
                if(originRoleID==1 || originRoleID == 6 ||menu_customer_modify){
                    tr_div+="<a href='#' class='modify_btn' style='margin-bottom: 5px;' data-id='" + _result[i].CustomerID + "'>"+_("修改")+"</a>";// onclick='modify_box(this)'
                }
                if(originRoleID==1 || menu_customer_cash_withdrawal){
                    tr_div += "<a href='#' class='Withdrawals_btn' style='margin-bottom: 5px;' data-id='" + _result[i].CustomerID + "'>"+_("提现")+"</a>";// onclick='Cash_Js(this)'
                }
                if(originRoleID ==1 || menu_customer_adjust ){
                    tr_div += "<a href='#' class='adjust_btn' data-id='" + _result[i].CustomerID + "'>"+_("调节")+"</a></div></td></tr>";// onclick='Adjust_Js(this)'
                }
            }
            else if(_result[i].SysStatus == 1 && (_result[i].Balance > 0 || _result[i].USDBalance > 0)){
                tr_div += "<div class='handle_div'>";
                    //                       "<a href='#' class='edit_power_btn' data-id='" + _result[i].CustomerID + "'>"+_("权限")+"</a>"+
                    if(originRoleID==1 || originRoleID ==3 || originRoleID == 6 || menu_customer_power){
                        tr_div+="<a href='#' class='power_btn' data-id='" + _result[i].CustomerID + "'>"+_("权限")+"</a>";
                    }
                    if(originRoleID==1 || originRoleID == 6 ||menu_customer_modify){
                        tr_div+= "<a href='#' class='modify_btn' style='margin-bottom: 5px;' data-id='" + _result[i].CustomerID + "'>"+_("修改")+"</a>";//onclick='modify_box(this)'
                    }
                if(originRoleID==1 ||  menu_customer_cash_withdrawal){
                    tr_div +="<a href='#' class='Withdrawals_btn' data-id='" + _result[i].CustomerID + "'>"+_("提现")+"</a>";
                }
                tr_div +="</div></td></tr>";// onclick='Cash_Js(this)'
            }
            else{
                tr_div += "<div class='handle_div'>";
                    //                      "<a href='#' class='edit_power_btn' data-id='" + _result[i].CustomerID + "'>"+_("权限")+"</a>"+
                    if(originRoleID==1 || originRoleID ==3 || originRoleID == 6 || menu_customer_power){
                        tr_div+="<a href='#' class='power_btn' data-id='" + _result[i].CustomerID + "'>"+_("权限")+"</a>";
                    }
                    if(originRoleID==1 || originRoleID == 6 ||menu_customer_modify){
                        tr_div+=  "<a href='#' class='modify_btn' data-id='" + _result[i].CustomerID + "'>"+_("修改")+"</a>";
                    }
                    tr_div+="</div></td></tr>";
            }
//                  tr_div+="<div style='height:30px;clear:both'>"+ _result[i].CustomerID+"</div></td></tr>";
            trs += tr+tr_div;//将单行加到多行

        }

        tableTbody.html(trs);//加入到id为customer的table的tbody中
        currentShow();  //币种设置
        myApp.hideIndicator();//隐藏加载中
        //下拉框优化 10-28
        var options = "";
        var options1 = "";
        options += '<option value="">'+_("帐号")+'</option>';
        options1 += '<option value="">'+_("昵称")+'</option>';

        for (var i = 0; i < _result.length; i++) {
            options += '<option value="' +  $.trim(_result[i].UserName)+ '"  >' +$.trim(_result[i].UserName) + '</option>';//解决因为空格导致帐号无法搜索 10-27
            options1 += '<option value="' +  $.trim(_result[i].NickName)+ '"  >' +$.trim(_result[i].NickName) + '</option>';//解决因为空格导致帐号无法搜索 10-27

        }
        $("#_customerUserName").html("");//客户帐号搜索下拉
        $("#_customerUserName").html(options);

        $("#_customerNickName").html("");//客户昵称搜索下拉 10-29
        $("#_customerNickName").html(options1);
    }
}
